package controllers

import (
	"github.com/astaxie/beego"
	"github.com/satori/go.uuid"
	"github.com/astaxie/beego/orm"
	"huxiaopang/models"
	"strings"
	"time"
)

type TableCodeController struct {
	ApiBaseController
}

// @router /gettablecode [post]
func (this *TableCodeController) GetTableCode() {
	bean := BaseBean{}
	storeCode := this.GetString("store_code")
	if len(storeCode) == 0 {
		bean.Code = "-1"
		bean.Message = "store_code不能为空"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}

	tableCode := this.GetString("table_code")
	if len(tableCode) == 0 {
		bean.Code = "-1"
		bean.Message = "table_code不能为空"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}

	if checkStorePermission(storeCode){
		linkaddress := createTableCode(storeCode, tableCode)
		if(len(linkaddress) == 0){
			bean.Code = "-1"
			bean.Message = "生成链接失败"
			this.Data["json"] = bean
			this.ServeJSON()
			return
		}else {
			this.Data["json"] = map[string]interface{}{
				"code": "0",
				"msg":  "SUCCESS",
				"data": linkaddress,
			}
			this.ServeJSON()
			return
		}
	}else{
		bean.Code = "-1"
		bean.Message = "该门店没有权限"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}




}

func createTableCode(storeCode string, tableCode string) string {

	tableNumberData := models.TableNumberData{}
	tableNumberData.StoreCode = storeCode
	tableNumberData.TableCode = tableCode
	if err := tableNumberData.Read("StoreCode", "TableCode"); err != nil {
		//查询不到,插入
		uuid := getUUID()
		now_time := time.Now().Format("20060102150405")
		data := models.TableNumberData{}
		data.StoreCode = storeCode
		data.TableCode = tableCode
		data.Uuid = uuid
		data.CreateTime = now_time
		data.LinkAddress = HOST + "tablecode/tablecodelink?uuid=" + uuid
		data.Insert()
		return data.LinkAddress
	}else {
		return tableNumberData.LinkAddress
	}
	return ""
}

func getUUID() string{
	ul, _ := uuid.NewV4()
	uuid := ul.String()
	return strings.Replace(uuid, "-", "", -1)
}

func checkStorePermission(storeCode string) bool{
	beego.Debug(storeCode)

	storePermissionData := models.StorePermissionData{}
	storePermissionData.StoreCode = storeCode

	if err := storePermissionData.Read("StoreCode");  err != nil && err!=orm.ErrNoRows{
		return false
	}else if err == orm.ErrNoRows{
		return false
	}else {
		if(storePermissionData.TableCodePermission == "Y"){
			return true
		}else{
			beego.Debug("不等于Y")
			return false
		}
	}
	return false
}

// @router /tablecodelink [post,get]
func (this *TableCodeController) Link() {
	bean := BaseBean{}
	uuid := this.GetString("uuid")

	beego.Debug(uuid)
	if len(uuid) == 0 {
		bean.Code = "-1"
		bean.Message = "uuid不能为空"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}

	tableNumberData := models.TableNumberData{}
	tableNumberData.Uuid = uuid

	
	if err := tableNumberData.Read("Uuid"); err != nil && err!=orm.ErrNoRows{
		this.Data["err_msg"] = "系统繁忙"
		this.TplName = "err.html"
	}else if err == orm.ErrNoRows{
		//错误页面
		this.Data["err_msg"] = "该商户没有此桌码"
		this.TplName = "err.html"
	}else {
		if !checkStorePermission(tableNumberData.StoreCode) {
			//未知来源
			this.Data["err_msg"] = "没有权限"
			this.TplName = "err.html"
			return
		}

		storePermissionData := models.StorePermissionData{}
		storePermissionData.StoreCode = tableNumberData.StoreCode
		storePermissionData.Read("StoreCode")

		userAgent := this.Ctx.Request.Header.Get("User-Agent")
		beego.Debug("userAgent:" + userAgent)
		if len(userAgent) != 0 && strings.Contains(userAgent, "AlipayClient") {
			//支付宝
			this.Data["UUID"] = tableNumberData.Uuid
			this.Data["Channel"] = "ALIPAY"
			this.Data["TableCode"] = tableNumberData.TableCode
			this.Data["StoreCode"] = tableNumberData.StoreCode
			this.Data["StoreName"] = storePermissionData.StoreName
			this.TplName = "index.html"
		}else if len(userAgent) != 0 && strings.Contains(userAgent, "MicroMessenger") {
			//微信
			this.Data["UUID"] = tableNumberData.Uuid
			this.Data["Channel"] = "WECHAT"
			this.Data["TableCode"] = tableNumberData.TableCode
			this.Data["StoreCode"] = tableNumberData.StoreCode
			this.Data["StoreName"] = storePermissionData.StoreName
			this.TplName = "wxindex.html"
		}else {
			//未知来源
			this.Data["err_msg"] = "未知来源"
			this.TplName = "err.html"
		}
	}

}


// @router /deltablecode [post]
func (this *TableCodeController) DelTableCode() {
	bean := BaseBean{}
	storeCode := this.GetString("store_code")
	if len(storeCode) == 0 {
		bean.Code = "-1"
		bean.Message = "store_code不能为空"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}

	tableCode := this.GetString("table_code")
	if len(tableCode) == 0 {
		bean.Code = "-1"
		bean.Message = "table_code不能为空"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}
	
	/*
	tableNumberData := models.TableNumberData{}
	tableNumberData.StoreCode = storeCode
	tableNumberData.TableCode = tableCode

	if err := tableNumberData.Read("StoreCode", "TableCode"); err != nil && err!=orm.ErrNoRows{
		bean.Code = "-1"
		bean.Message = "删除失败"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}else if err == orm.ErrNoRows{
		bean.Code = "-1"
		bean.Message = "此门店没有该桌码"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}else {
		if err := tableNumberData.Delete(); err != nil{
			bean.Code = "-1"
			bean.Message = "删除失败"
			this.Data["json"] = bean
			this.ServeJSON()
			return
		}else {
			bean.Code = "0"
			bean.Message = "删除成功"
			this.Data["json"] = bean
			this.ServeJSON()
			return
		}

	}
	*/

	o := orm.NewOrm()
	o.Begin() //开事物
	tableNumberCode := models.TableNumberData{StoreCode:storeCode, TableCode:tableCode}
	if err := o.Read(&tableNumberCode,  "StoreCode", "TableCode"); err == orm.ErrNoRows {
		o.Rollback()
		bean.Code = "-1"
		bean.Message = "查询不到"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	} else if err == orm.ErrMissPK {
		o.Rollback()
		bean.Code = "-1"
		bean.Message = "找不到主键"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	} else {
		if _, err := o.Delete(&tableNumberCode, "StoreCode", "TableCode"); err == nil{
			//删除device_tablecode_data中的数据
			deviceTableCodeData := models.DeviceTableCodeData{StoreCode:storeCode, TableCode:tableCode}
			if _, err := o.Delete(&deviceTableCodeData, "StoreCode", "TableCode"); err != nil && err!=orm.ErrNoRows{
				o.Rollback()
				bean.Code = "-1"
				bean.Message = "删除失败"
				this.Data["json"] = bean
				this.ServeJSON()
				return
			}else if err == orm.ErrNoRows{
				o.Commit()
				this.Data["json"] = map[string]interface{}{
					"code": "0",
					"msg":  "SUCCESS",
					"data": "删除成功",
				}
				this.ServeJSON()
				return
			}else {
				o.Commit()
				this.Data["json"] = map[string]interface{}{
					"code": "0",
					"msg":  "SUCCESS",
					"data": "删除成功",
				}
				this.ServeJSON()
				return
			}
		}else {
			o.Rollback()
			bean.Code = "-1"
			bean.Message = "删除失败"
			this.Data["json"] = bean
			this.ServeJSON()
			return
		}
	}
}

// @router /edittablecode [post]
func (this *TableCodeController) EditTableCode() {
	bean := BaseBean{}
	storeCode := this.GetString("store_code")
	if len(storeCode) == 0 {
		bean.Code = "-1"
		bean.Message = "store_code不能为空"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}

	oldTableCode := this.GetString("old_table_code")
	if len(oldTableCode) == 0 {
		bean.Code = "-1"
		bean.Message = "old_table_code不能为空"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}

	newTableCode := this.GetString("new_table_code")
	if len(newTableCode) == 0 {
		bean.Code = "-1"
		bean.Message = "new_table_code不能为空"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}


	tableNumberData := models.TableNumberData{}
	tableNumberData.StoreCode = storeCode
	tableNumberData.TableCode = newTableCode
	if err := tableNumberData.Read("StoreCode", "TableCode"); err == nil{
		bean.Code = "-1"
		bean.Message = "此桌号已存在"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}
	
	o := orm.NewOrm()
	o.Begin() //开事物
	tableNumberCode := models.TableNumberData{StoreCode:storeCode, TableCode:oldTableCode}
	if err := o.Read(&tableNumberCode,  "StoreCode", "TableCode"); err == orm.ErrNoRows {
		o.Rollback()
		bean.Code = "-1"
		bean.Message = "查询不到"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	} else if err == orm.ErrMissPK {
		o.Rollback()
		bean.Code = "-1"
		bean.Message = "找不到主键"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	} else {
		//
		tableNumberCode.TableCode = newTableCode
		if _, err := o.Update(&tableNumberCode,  "TableCode"); err == nil {
			//更新device_tablecode_data中的数据
			deviceTableCodeData := models.DeviceTableCodeData{StoreCode:storeCode, TableCode:oldTableCode}
			if err := o.Read(&deviceTableCodeData,  "StoreCode", "TableCode"); err == orm.ErrNoRows {
				o.Commit()
				bean.Code = "0"
				bean.Message = "更新成功"
				this.Data["json"] = bean
				this.ServeJSON()
				return
			} else if err == orm.ErrMissPK {
				o.Rollback()
				bean.Code = "-1"
				bean.Message = "更新失败"
				this.Data["json"] = bean
				this.ServeJSON()
				return
			} else {
				deviceTableCodeData.TableCode = newTableCode
				if _, err := o.Update(&deviceTableCodeData,  "TableCode"); err == nil {
					o.Commit()
					bean.Code = "0"
					bean.Message = "更新成功"
					this.Data["json"] = bean
					this.ServeJSON()
					return
				}else {
					o.Rollback()
					bean.Code = "-1"
					bean.Message = "更新失败"
					this.Data["json"] = bean
					this.ServeJSON()
					return
				}
			}
		}else {
			o.Rollback()
			bean.Code = "-1"
			bean.Message = "更新失败"
			this.Data["json"] = bean
			this.ServeJSON()
			return
		}


	}
}